package config

import (
	"os"

	"github.com/BurntSushi/toml"
	"github.com/sirupsen/logrus"
)

// Config 应用程序配置结构体
type Config struct {
	Document   DocumentConfig   `toml:"document"`
	Embedding  EmbeddingConfig  `toml:"embedding"`
	Indexer    IndexerConfig    `toml:"indexer"`
	Retriever  RetrieverConfig  `toml:"retriever"`
	Model      ModelConfig      `toml:"model"`
	Service    ServiceConfig    `toml:"service"`
	Monitoring MonitoringConfig `toml:"monitoring"`
}

// DocumentConfig 文档处理配置
type DocumentConfig struct {
	Loader      LoaderConfig      `toml:"loader"`
	Transformer TransformerConfig `toml:"transformer"`
}

// LoaderConfig 文档加载配置
type LoaderConfig struct {
	SupportedFormats []string `toml:"supported_formats"`
	Timeout          int      `toml:"timeout"`
}

// TransformerConfig 文档转换配置
type TransformerConfig struct {
	Strategy     string `toml:"strategy"`
	MaxChunkSize int    `toml:"max_chunk_size"`
	ChunkOverlap int    `toml:"chunk_overlap"`
	MinChunkSize int    `toml:"min_chunk_size"`
}

// EmbeddingConfig 向量嵌入配置
type EmbeddingConfig struct {
	Type         string `toml:"type"`
	EmbeddingDim int    `toml:"embedding_dim"`
	BatchSize    int    `toml:"batch_size"`
	ModelPath    string `toml:"model_path"`
	ModelName    string `toml:"model_name"` // 嵌入模型名称
	ServerURL    string `toml:"server_url"` // 嵌入服务URL
}

// IndexerConfig 向量索引配置
type IndexerConfig struct {
	Type             string `toml:"type"`
	IndexPath        string `toml:"index_path"`
	StoragePath      string `toml:"storage_path"`
	UseGPU           bool   `toml:"use_gpu"`
	MilvusType       string `toml:"milvus_type"`
	MilvusHost       string `toml:"milvus_host"`
	MilvusPort       int    `toml:"milvus_port"`
	MilvusUser       string `toml:"milvus_user"`
	MilvusPassword   string `toml:"milvus_password"`
	MilvusCollection string `toml:"milvus_collection"`
}

// RetrieverConfig 检索配置
type RetrieverConfig struct {
	RetrieverType       string           `toml:"retriever_type"`
	TopK                int              `toml:"top_k"`
	SimilarityThreshold float64          `toml:"similarity_threshold"`
	EnableRerank        bool             `toml:"enable_rerank"`
	MultiQuery          MultiQueryConfig `toml:"multi_query"`
}

// MultiQueryConfig 多查询配置
type MultiQueryConfig struct {
	MaxQueries    int    `toml:"max_queries"`
	RewritePrompt string `toml:"rewrite_prompt"`
}

// ModelConfig 模型配置
type ModelConfig struct {
	Type            string  `toml:"type"`              // 模型类型: local, openai, ollama, zhipuai
	ModelPath       string  `toml:"model_path"`        // 本地模型路径
	ModelName       string  `toml:"model_name"`        // 模型名称
	Temperature     float32 `toml:"temperature"`       // 生成温度
	MaxTokens       int     `toml:"max_tokens"`        // 最大生成token数
	SystemPrompt    string  `toml:"system_prompt"`     // 系统提示词
	BaseURL         string  `toml:"base_url"`          // API基础URL
	Timeout         int     `toml:"timeout"`           // 超时时间(秒)
	AzureEnabled    bool    `toml:"azure_enabled"`     // 是否启用Azure
	AzureBaseURL    string  `toml:"azure_base_url"`    // Azure基础URL
	AzureAPIVersion string  `toml:"azure_api_version"` // Azure API版本
}

// ServiceConfig 服务配置
type ServiceConfig struct {
	Port       int            `toml:"port"`
	LogLevel   string         `toml:"log_level"`
	EnableCORS bool           `toml:"enable_cors"`
	Cache      CacheConfig    `toml:"cache"`
	Redis      RedisConfig    `toml:"redis"`
	ArkAPI     ArkAPIConfig   `toml:"ark_api"`
	AgentAPI   AgentAPIConfig `toml:"agent_api"`
}

// RedisConfig Redis配置
type RedisConfig struct {
	Enable    bool   `toml:"enable"`
	Host      string `toml:"host"`
	Port      int    `toml:"port"`
	Password  string `toml:"password"`
	DB        int    `toml:"db"`
	IsCluster bool   `toml:"is_cluster"`
}

// ArkAPIConfig Ark API配置
type ArkAPIConfig struct {
	Enabled bool   `toml:"enabled"`
	APIKey  string `toml:"api_key"`
	APIURL  string `toml:"api_url"`
}

// AgentAPIConfig Agent API配置
type AgentAPIConfig struct {
	Enabled bool   `toml:"enabled"`
	Host    string `toml:"host"`
	AK      string `toml:"ak"`
	SK      string `toml:"sk"`
}

// CacheConfig 缓存配置
type CacheConfig struct {
	Enable     bool `toml:"enable"`
	Expiration int  `toml:"expiration"`
	MaxEntries int  `toml:"max_entries"`
}

// MonitoringConfig 监控配置
type MonitoringConfig struct {
	Enable   bool `toml:"enable"`
	Interval int  `toml:"interval"`
}

// LoadConfig 从文件加载配置
func LoadConfig(configPath string) (*Config, error) {
	content, err := os.ReadFile(configPath)
	if err != nil {
		logrus.WithError(err).Error("读取配置文件失败")
		return nil, err
	}

	var config Config
	if err := toml.Unmarshal(content, &config); err != nil {
		logrus.WithError(err).Error("解析配置文件失败")
		return nil, err
	}

	logrus.Info("配置文件加载成功")
	return &config, nil
}
